package com.flyduck.mall.sms.h5.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.mall.common.core.utils.BeanUtils;
import com.flyduck.mall.sms.document.EsProductDoc;
import com.flyduck.mall.sms.h5.service.H5EsProductService;
import com.flyduck.mall.sms.h5.vo.H5EsProductRespVO;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * AppSearchServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-05-24
 */
@Service
public class H5EsProductServiceImpl implements H5EsProductService {

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Page<H5EsProductRespVO> getEsProductPage(String keyword, int current, int size) {

        Criteria criteria = new Criteria("name").matches(keyword)
                .or(
                        new Criteria("keyword").matches(keyword)
                );

        //springDataJpa的分页从0开始，所以current-1
        Query query = new CriteriaQuery(criteria).setPageable(PageRequest.of(current - 1, size));

        SearchHits<EsProductDoc> searchHits = elasticsearchTemplate.search(query, EsProductDoc.class);
        List<EsProductDoc> esProductDocList = searchHits.get().map(SearchHit::getContent).collect(Collectors.toList());
        List<H5EsProductRespVO> h5EsProductRespVOList = BeanUtils.toBeanList(esProductDocList, H5EsProductRespVO.class);

        Page<H5EsProductRespVO> page = new Page<>(current,size,searchHits.getTotalHits());
        page.setRecords(h5EsProductRespVOList);
        return page;
    }
}
